import Router from 'koa-router';
import axios from './util/axios'
import publicIp from 'public-ip'
//模型
import Menu from '../dbs/models/menu'
import Province from '../dbs/models/province'
import City from '../dbs/models/city'

let router = new Router({prefix: '/geo'})

router.get('/getPosition', async (ctx) => {

  let ip = ctx.request.ips[0] || await publicIp.v4()
  console.log(ip)
  // 高德地图api
  let res = await axios.get(`https://restapi.amap.com/v3/ip?ip=${ip}&key=a410978db3b8829f4ac07db7818bcec3` )
  ctx.body = {
    status:true,
    data: {
      province: Array.isArray(res.province) ? '广东': res.province,
      city: Array.isArray(res.city) ? '深圳': res.city,
    }
  }
})
// 菜单接口
router.get('/menu', async (ctx) => {
  const result = await Menu.findOne()
  ctx.body = {
    status: true,
    data: result.menu
  }
})

/**
 * 城市接口
 * */
router.get('/province', async (ctx) => {
  let province = await Province.find()
  ctx.body = {
    status: true,
    data: province.map(item => {
      return {
        id: item.id,
        name: item.name
      }
    })
  }

})
router.get('/city', async (ctx) => {
  let city = []
  let result = await City.find()
  result.forEach(item => {
    city = city.concat(item.value)
  })
  ctx.body = {
    status: true,
    city: city.map(item => {
      return {
        province: item.province,
        id: item.id,
        name: item.name === '市辖区' || item.name === '省直辖县级行政区划'
          ? item.province
          : item.name
      }
    })
  }

})
router.get('/province/:id', async (ctx) => {
  let res = await City.findOne({id: ctx.params.id})
  ctx.body = res
  ctx.body = {
    status: true,
    city: res.value.map(item => {
      return {province: item.province, id: item.id, name: item.name}
    })
  }
})
router.get('/hotCity', async (ctx) => {
  let list = [
    '北京市',
    '上海市',
    '广州市',
    '深圳市',
    '天津市',
    '西安市',
    '重庆市',
    '杭州市',
    '南京市',
    '武汉市',
    '成都市'
  ]
  let result = await City.find()
  let nList = []
  result.forEach(item => {
    nList = nList.concat(item.value.filter(k => list.includes(k.name) || list.includes(k.province)))
  })
  ctx.body = {
    status: true,
    hots: nList
  }
})
export default router;

